package org.nutz.easy.view;

import java.io.BufferedWriter;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.castor.Castors;
import org.nutz.lang.Strings;
import org.nutz.mvc.View;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

/**
 * <p>实现集成freemarker模板引擎 </p>
 * @author defier Lai
 * <p>Date: 2009-10-3 下午03:33:00</p>
 * @version 1.0
 */
public class FreeMarkerView implements View {

	private String path;
	private String name;
	private Object obj;
	
	private Configuration cfg = new Configuration();
	
	public FreeMarkerView() {
		
	}
	
	public Configuration getCfg() {
		return cfg;
	}
	
	public FreeMarkerView(String name) {
		this.name = name;
	}
	
	public String getPath() {
		if(Strings.isEmpty(name)) {
			this.path = new StringBuilder("/views/share").toString();
		} else if(name.indexOf(".") > 0) {
			this.path = new StringBuilder("/views/").toString();
		} else if("error".equals(name)) {
			this.path = new StringBuilder("/views/share").toString();
		} else {
			this.path = new StringBuilder("/views/" + obj.getClass().getSimpleName().toLowerCase() + "/").toString();
		}
		return path;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void render(HttpServletRequest request,
			HttpServletResponse response, Object obj) throws Throwable {
		this.obj = obj;
		this.path = request.getContextPath();
		Map map = new HashMap();
		if (obj instanceof Collection) {
			for (Object ele : (Collection) obj) {
				map.putAll(Castors.me().castTo(ele, Map.class));
			}
		} else if (obj instanceof Map) {
			map = (Map) obj;
		} else {
			map = Castors.me().castTo(obj, Map.class);
		}
        
		String path = getPath();
//		getCfg().setDirectoryForTemplateLoading(new File(path));
		getCfg().setTemplateLoader(new FileTemplateLoader(new File(request.getSession().getServletContext().getRealPath(path))));
		getCfg().setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
		getCfg().setDefaultEncoding("utf-8");
		Template t = getCfg().getTemplate(getTemplateName() + ".ftl");
		StringWriter stringWriter = new StringWriter();   
        BufferedWriter writer = new BufferedWriter(stringWriter);
		t.process(map, writer);
		writer.flush();
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.println(stringWriter.toString());
		out.flush();
		out.close();
		
	}
	
	private String getTemplateName() {
		if(Strings.isEmpty(this.name)) {
			this.name = "error";
		}
		return this.name;
	}

}
